package com.lambda.hybrid.handler;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

import com.lambda.hybrid.Callback;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;

public class ShowAlertHandler extends AbstractHandler {
    private WeakReference<Context> mContextRef;

    public ShowAlertHandler(Context context) {
        mContextRef = new WeakReference<>(context);
    }

    @Override
    public void onHandle(String data, Callback cb) throws Exception {
        Context context = mContextRef.get();
        if (context == null) return;

        JSONObject paramTable = new JSONObject(data);

        AlertDialog.Builder builder = new AlertDialog.Builder(context)
                .setTitle(paramTable.optString("title"))
                .setMessage(paramTable.getString("message"))
                .setPositiveButton(
                        paramTable.optString("confirmTitle", "确定"),
                        new OnDialogClickListener(cb, 1)
                ).setNegativeButton(
                        paramTable.optString("cancelTitle", "取消"),
                        new OnDialogClickListener(cb, 0)
                );
        if (!paramTable.has("cancelable") || !paramTable.getBoolean("cancelable")) {
            builder.setCancelable(false);
        } else {
            builder.setCancelable(true).setOnCancelListener(new OnDialogCancelListener(cb));
        }

        builder.show();
    }

    private static class OnDialogCancelListener implements DialogInterface.OnCancelListener {
        private final Callback cb;

        private OnDialogCancelListener(Callback cb) {
            this.cb = cb;
        }

        @Override
        public void onCancel(DialogInterface dialog) {
            if (cb == null) return;

            JSONObject response = new JSONObject();
            try {
                response.put("buttonIndex", -1);
            } catch (JSONException e) {/**/}
            cb.invoke(response.toString());
        }
    }

    private static class OnDialogClickListener implements DialogInterface.OnClickListener {
        private final Callback cb;
        private final int idx;

        private OnDialogClickListener(Callback cb, int idx) {
            this.cb = cb;
            this.idx = idx;
        }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (cb == null) return;

            JSONObject response = new JSONObject();
            try {
                response.put("buttonIndex", idx);
            } catch (JSONException e) {/**/}
            cb.invoke(response.toString());
        }
    }
}
